package com.zy.socket;

import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Gong
 * @Description
 * @dATE 2021/12/16 17:03
 **/
public class ThreadServer extends Thread{
    public static List<PrintWriter> printspool=new ArrayList<>();
    public static List<Socket> socketspool=new ArrayList<>();
    private Socket socket;
    ThreadServer(Socket socket){
        this.socket = socket;

    }
    //发送广播信息给所有的socket
    public void sendToAllSocket(String info){
        if(null!= info && info.length() > 0){
            PrintWriter pw = null;
            for(Socket socket:socketspool){
                //但是排除发送者自己
                if(socket.hashCode() != this.socket.hashCode()){
                    OutputStream os = null;
                    try {
                        os = socket.getOutputStream();
                        OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
                        pw = new PrintWriter(osw, true);
                        pw.println(info);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
        }
    }

    /**
     * @Author GongXL
     * @Description  广播信息
     * @Date 23:36 2021/12/16
     * @Param [java.lang.String]
     * @return void
     **/
    public void sendToAll(String info){
        if(null!= info && info.length() > 0){
            for (PrintWriter o : printspool) {
                o.println(info);
            }
        }
    }
    @Override
    public void run() {
        PrintWriter pw = null;

        System.out.println("服务器链接成功：" + this.socket);
        DataInputStream din = null;
        try {
            OutputStream os = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
            pw = new PrintWriter(osw, true);
            //存入共享集合
            printspool.add(pw);
            socketspool.add(socket);

            InputStream is = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "UTF-8");
            BufferedReader br = new BufferedReader(isr);

            String message = null;
            //接受客户端信息
            while ((message = br.readLine()) != null) {
                String res = socket.hashCode()+"say:"+message;
                System.out.println(res);
//                sendToAll(res);
                //广播给所有的客户端
                sendToAllSocket(res);
            }

        } catch (Exception e) {
            e.printStackTrace();
            printspool.remove(this.socket);
        }finally{
            //当客户端断线时，要将输出流从集合中删除
            printspool.remove(pw);
            if (socket != null) {
                try {
                    socket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
